import traceback

from apps.event.serializer import EventActionSerializer
from apps.event.display import ActionNameMap
from models.task import ScanEvents
from utilities.meta_view import Response, APIViewUpdate
from utilities.log import audit_log
from utilities.enums import LogModuleName, AuditLogAction, LogTypeName
from wass.display import LANGUAGE_CODE


class ScanSessionActionHandle(APIViewUpdate):
    serializer_class = EventActionSerializer
    queryset = EventActionSerializer.Meta.model.objects
    lookup_field = 'event_id'

    def update(self):
        event_id_list = self.request.data.pop('event_ids', [])

        event_id_set = {item.event_id for item in ScanEvents.objects.find(
            {self.lookup_field: {'$in': event_id_list}, **self.user_query})}
        if event_id_set != set(event_id_list):
            raise self.permission_denied(self.request)

        for event_id in event_id_list:
            request_data = {'event_id': event_id, **self.request.data}
            try:
                instance = self.queryset.find_one(
                    {self.lookup_field: request_data[self.lookup_field]}
                )

                if not instance:
                    event = ScanEvents.objects.get(
                        **{self.lookup_field: request_data[self.lookup_field]}
                    ).to_dict()

                    data = {**event, **request_data}
                    serializer = self.get_serializer(instance, data=data)
                    serializer.is_valid(raise_exception=True)
                    self.perform_create(serializer)
                else:
                    data = {**instance.to_dict(), **request_data}
                    serializer = self.get_serializer(instance, data=data)
                    serializer.is_valid(raise_exception=True)
                    self.perform_update(serializer)
            except Exception:
                traceback.print_exc()

        data = {
            "module": LogModuleName.task_management.value,
            "action": AuditLogAction.up.value,
            "type": LogTypeName.task.value,
            "desc": {"detail": f"批量修改事件状态为"
                               f" '{ActionNameMap.get(LANGUAGE_CODE, {}).get(self.request.data.get('action', 0))}'"},
        }
        audit_log(request=self.request, **data)

        return Response({'status': 'success'})
